'use strict';

module.exports = class extends think.Controller {
  // 登陆
  async signinAction() {
    if (this.isPost) {
      const username = this.post('username');
      const password = think.md5(this.post('password'));

      // 查询是否有用户名
      const userinfo = await this.model('or_admin').where({username: username}).find();

      if (think.isEmpty(userinfo)) {
        return this.fail('用户名不存在！');
      } else if (password !== userinfo.password) {
        return this.fail('密码错误！');
      } else {
        // 根据departmentid分别赋值session类型
        const departmentinfo = await this.model('or_department').where({id: userinfo.departmentid}).find();
        departmentinfo.floor == 1 ? await this.session('shop_userinfo', userinfo) : await this.session('or_userinfo', userinfo);
        const permission = await this.model('or_rule_admin').where({id: userinfo.groupid}).find();

        const data = {
          floor: departmentinfo.floor,
          permi: permission
        };
        return this.success(data);
      }
    }
    return this.json({isrelogin: 1});
  }

  async newsigninAction() {
    const username = this.post('username');
    const password = think.md5(this.post('password'));
    const machineid = this.post('machineid');

    const userinfo = await this.model('or_admin').where({username: username}).find();

    if (think.isEmpty(userinfo)) {
      return this.fail('用户名不存在！');
    } else if (password !== userinfo.password) {
      return this.fail('密码错误！');
    } else {
      // 验证通过后进行下一步
      // 生成token
      // 机器码简单加密
      const simpleSceret = {
        machineid: machineid
      };
      // 特殊加密
      const specialSecret = {
        uid: userinfo.id,
        time: Math.round(new Date().valueOf() / 1000)
      };
      const S = require('./secret.js');
      const secret = new S();
      const basetoken = secret.cipherbase64(simpleSceret) + '.' + secret.cipherbase64(specialSecret);
      const lasttoken = secret.createHmac(basetoken);
      const token = basetoken + '.' + lasttoken;

      // 下面的验证还是暂时正常运作

      // 根据departmentid分别赋值session类型
      const departmentinfo = await this.model('or_department').where({id: userinfo.departmentid}).find();
      departmentinfo.floor == 1 ? await this.session('shop_userinfo', userinfo) : await this.session('or_userinfo', userinfo);
      const permission = await this.model('or_rule_admin').where({id: userinfo.groupid}).find();
      const user = {
        id: userinfo.id,
        name: userinfo.name,
        headimg: userinfo.headimg
      };
      const data = {
        floor: departmentinfo.floor,
        permi: permission,
        token: token,
        userinfo: user
      };
      return this.success(data);
    }
  }

  // 登出
  async logoutAction() {
    await this.session('or_userinfo', null);
    await this.session('shop_userinfo', null);
    return this.success('退出成功！');
  }

  // 获取七牛上传图片的验证token
  async gettokenAction() {
    const qiniu = require('qiniu');
    // 需要填写你的 Access Key 和 Secret Key
    qiniu.conf.ACCESS_KEY = this.config('qiniu.ACCESS_KEY');
    qiniu.conf.SECRET_KEY = this.config('qiniu.SECRET_KEY');
    // 要上传的空间
    const bucket = this.config('qiniu.BUCKET');

    const mac = new qiniu.auth.digest.Mac(qiniu.conf.ACCESS_KEY, qiniu.conf.SECRET_KEY);
    const putPolicy = new qiniu.rs.PutPolicy({
      scope: bucket
    });
    const uploadToken = putPolicy.uploadToken(mac);

    const data = {'uptoken': uploadToken};
    return this.json(data);
  }

  // 获取左侧的分类列表
  async getMenuAction() {
    const mlist = await this.model('menu').where({status: 1, is_hidden: 0}).select();
    return this.json(mlist);
  }

  // 获取当前用户的权限信息
  async getpermissioninfoAction() {
    const data = this.post();
    console.log(data);
    return this.fail('.....');
  }

  // 获取最新版本号
  async getversionAction() {
    const version = await this.model('config').where({id: 1}).find();
    return this.json(version);
  }

  async getexcelAction() {
    var xlsx = require('node-xlsx');
    var fs = require('fs');

    const data = [[1, 2, 3], [true, false, null, 'sheetjs'], ['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'], ['baz', null, 'qux']];
    var buffer = xlsx.build([{name: 'mySheetName', data: data}]); // Returns a buffer

    // fs.writeFileSync('b.xlsx', buffer, 'binary');
    // this.ctx.respond = false
    console.log(this.ctx.res);
    /* this.ctx.set('Content-Type', 'application/vnd.openxmlformats');
      this.ctx.set("Content-Disposition", "attachment; filename=" + "Report.xlsx");
      this.ctx.end(buffer, 'binary'); */

    this.header('Content-Description', 'File Transfer');
    this.header('Content-Type', 'application/csv; charset=utf-8');
    this.header('Content-Disposition', 'attachment; filename=data.csv');
    this.header('Expires', '0');
    this.header('Cache-Control', 'must-revalidate');
    this.ctx.set('Content-Type', 'application/vnd.openxmlformats');
    this.ctx.set('Content-Disposition', 'attachment; filename=o2olog.xlsx');
    this.ctx.type = 'application/csv';
    this.ctx.body = buffer;
    return false;
  }
};
